var app = getApp()

Page({
  data: {
    id: null,
    survey: null,
    color: [
      "#ffbe26",
      "#fc5b23",
      "#198ded",
      "#3bc06b",
      "#c90ff0"
    ],
    currentpage:0,
    style: "wu",
    selectuserid: null,
    columncont: [],
    agemonthcount:[],
    answerrecordid:0,
    papername:'',
    rela:null,
    filename:null,
    covered:true,
    server: app.api.server,
    rightuserid:[],
    rightcheckuserid:[],
    rightusername:[]
  },
  onShareAppMessage: function() {
    var url = '/pages/show_questionnaire/show_questionnaire?id=' + this.data.id;
    console.log(url);

    var title = app.globalData.userInfo.nickName + "邀您填写" + "《" + this.data.survey.surveyname + "》"

    return {
      title: title,
      path: url,
    }
  },
  bindSwitchChange: function (e) {
    this.setData({
      covered: e.detail.value
    })
  },
  upload: function () {
    var that = this
    wx.chooseMessageFile({
      count: 1,     //能选择文件的数量
      type: 'file',   //能选择文件的类型,我这里只允许上传文件.还有视频,图片,或者都可以
      success(res) {
        var size = res.tempFiles[0].size;
        var filename = res.tempFiles[0].name;
        var newfilename = filename + "";

        if (size > 4194304 || newfilename.indexOf(".xlsx") == -1) { //我还限制了文件的大小和具体文件类型
          wx.showToast({
            title: '文件大小不能超过4MB,格式必须为xlsx！',
            icon: "none",
            duration: 2000,
            mask: true
          })
        } else {
          that.setData({
            path: res.tempFiles[0].path, //将文件的路径保存在页面的变量上,方便 wx.uploadFile调用
            filename: filename              //渲染到wxml方便用户知道自己选择了什么文件
          })
        }
      }
    })
  },

  submitFile: function () {
    var param = {};
    //param = this.data;
    param['covered'] = this.data.covered + '';
    param['surveyid'] = this.data.id + '';
    var filedata = [];
    filedata[0] = this.data.path;
    app.api.api_paper_upload(filedata, param, function (res) {
      wx.showToast({
        title: JSON.parse(res.data).message,
        icon: '',
        mask: true,
        duration: 1500
      })
    })
  },

  input_change: function(e) {
    var param = e.detail;
    param['surveyid'] = this.data.id;
    app.api.api_user_find(param).then(res => {
      this.selectComponent("#searchbar").setSelectVals(res);
    })
  },

  copycolumncont: function () {
    var copy = "";
    for (var item of this.data.columncont){
      copy += '栏目:' + item['columnname'] + ' 得分：' + item['count']+'\n';
    }
    app.api.copy(copy);
  },
  copyagemonthcount: function () {
    var copy = "";
    for (var item of this.data.agemonthcount) {
      copy += '月龄:' + item['columnname'] + ' 得分：' + item['count'] + '\n';
    }
    app.api.copy(copy);
  },
  exportdetail:function(){
    app.api.api_paper_downloaddetail({
      userid: this.data.selectuserid,
      surveyid: this.data.id,
      answerrecordid: this.data.answerrecordid
    },this.data.papername, function(){
      wx.showToast({
        title: '已下载',
        icon: 'none'
      })
    })
    
  },
  selected: function(e) {
    this.setData({
      selectuserid: e.detail.wechatuserid,
      papername:e.detail.name,
      answerrecordid: e.detail.answerrecordid
    })
    //展示汇总信息
    app.api.api_paper_usersurveycount({
      userid: this.data.selectuserid,
      surveyid: this.data.id,
      answerrecordid: this.data.answerrecordid
    }).then(res => {
      this.setData({
        columncont: res.count,
        agemonthcount: res.agecount,
      });
    })

    //更新详细答题为某个人的
    var thissurvey = this.data.survey;
    if (thissurvey){
      for (var itemques of thissurvey.queses) {
        for (var itemquesoption of itemques.optionsForQuesid) {
          var newanswer = [];
          for (var itemanswer of itemquesoption.answers) {
            if (this.data.rela.answer_user[itemanswer.answerid] === this.data.selectuserid) {
              newanswer.push(itemanswer);
            }
          }
          itemquesoption.answers = newanswer;
        }
      }
    }
    this.setData({
      survey: thissurvey
    })
  },

  input_changeuser: function(e) {
    var param = e.detail;
    param["surveyid"] = -1;
    app.api.api_user_find(param).then(res => {
      this.selectComponent("#searchbaruser").setSelectVals(res);
    })
  },
  selecteduser: function(e) {
    if(this.data.rightuserid.indexOf(e.detail.wechatuserid)>=0){
      return;
    }
    if(!e.detail.wechatuserid){
      app.api.api_showMsg("未绑定微信用户")
      return
    }
    var rightid = this.data.rightuserid ;
    var rightname = this.data.rightusername;
    rightid[rightid.length] = e.detail.wechatuserid;
    rightname[rightname.length] = e.detail.name;
    
    this.setData({rightuserid:rightid,rightusername:rightname});
    this.setcheckboxgroup();
  },
  saveright:function(){
    app.api.api_paper_rightsave({surveyid:this.data.id,
      userids:this.data.rightcheckuserid}).then(res=>function(res){
        app.api.api_showMsg(res);
    });
  },
  checkboxgroup_change:function(data){
    this.setData({rightcheckuserid:data.detail})
  },
  clearright:function(){// 不用了
    this.setData({rightuserid:[],rightusername:[]});
  },
  setcheckboxgroup:function(data){
    var array = [];
    for(var key in this.data.rightuserid){
      var checked= true;
      var obj = {key:this.data.rightuserid[key],name:this.data.rightusername[key]
                ,checked:checked};
      array[key] = obj;
    }
    this.selectComponent("#checkboxgroup").set_data({
      checksarray: array
    })
  },

  onLoad: function(e) {
    this.setData({
      id: e.id
    })
    wx.showNavigationBarLoading()
    var that = this;

    app.api.api_paper_rightinfo({surveyid:this.data.id}).then(res=>{
      console.log(res);
      this.selectComponent("#checkboxgroup").set_data({
        checksarray: res
      })
    })

    app.api.api_paper_rela({
      surveyid: this.data.id
    }).then(res => {
      this.setData({
        rela: res
      });
      wx.hideNavigationBarLoading();
    })    
    
  },
  loadquesdetail:function(e){
    var that = this;
    wx.request({
      url: this.data.server + '/statistics.action',
      data: {
        surveyid: parseInt(this.data.id),
      },
      method: 'POST',
      success: function (res) {
        debugger;
        // success
        that.setData({
          survey: res.data.surveyresponse
        })
        wx.hideNavigationBarLoading()
        wx.setNavigationBarTitle({
          title: that.data.survey.surveyname,
          success: function (res) {
            // success
          }
        })
        that.setData({currentpage:1});
        debugger;
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },

  godraw:function(e){
    wx.navigateTo({
      url: '../statistics/statisticscolumn?id=' + this.data.id + '&answerrecordid=' + this.data.answerrecordid + '&columnsize='+(this.data.columncont.length-1),
    })
  },

  changestyle: function() {
    var that = this;
    wx.showActionSheet({
      itemList: ['无图表', '条形图', '堆积图'],
      success: function(res) {
        console.log(res.tapIndex)
        if (res.tapIndex == 0) {
          that.setData({
            style: "wu"
          })
        } else if (res.tapIndex == 1) {
          that.setData({
            style: "tiaoxing"
          })
          that.drawtiaoxing()
        } else if (res.tapIndex == 2) {
          that.setData({
            style: "duiji"
          })
          that.drawduiji()
        }
      },
      fail: function(res) {
        console.log(res.errMsg)
      }
    })
  },
  drawduiji: function() {
    console.log("draw duiji")
    var that = this
    var res = wx.getSystemInfoSync()
    for (var i = 0; i < that.data.survey.queses.length; i++) {
      var question = that.data.survey.queses[i]
      var context = wx.createContext()
      var totalnumber = 0
      //获取所有人数充满屏幕宽度，以使每个选项有对应的宽度
      for (var j = 0; j < question.optionsForQuesid.length; j++) {
        totalnumber = totalnumber + question.optionsForQuesid[j].answers.length
      }

      var current = 0
      var horizontaloffset = 0;
      //开始绘制每个选项的图形条
      for (var k = 0; k < question.optionsForQuesid.length; k++) {
        var option = question.optionsForQuesid[k]

        horizontaloffset = current / totalnumber * res.windowWidth

        current = current + option.answers.length

        var width = option.answers.length / totalnumber * res.windowWidth
        //防止人数为0的时候没有长度显示
        if (width == 0)
          width = 2;

        context.beginPath()
        context.setFillStyle(that.data.color[k % that.data.color.length])
        context.rect(horizontaloffset, 0, width, res.windowWidth * 100 / 750)
        context.fill()
      }
      wx.drawCanvas({
        canvasId: 'Canvasduiji' + parseInt(i + 1),
        actions: context.getActions()
      })

    }
  },

  drawtiaoxing: function() {
    var that = this
    var res = wx.getSystemInfoSync()
    for (var i = 0; i < that.data.survey.queses.length; i++) {

      var question = that.data.survey.queses[i]
      var context = wx.createContext()
      var maxnumber = 0
      //获取最多人数的选项使图形充满屏幕宽度，其他选项根据比例调整长度
      for (var j = 0; j < question.optionsForQuesid.length; j++) {
        if (question.optionsForQuesid[j].answers.length > maxnumber) {
          maxnumber = question.optionsForQuesid[j].answers.length
        }
      }

      //开始绘制每个选项的图形条
      for (var k = 0; k < question.optionsForQuesid.length; k++) {
        var option = question.optionsForQuesid[k]
        var recheight = res.windowWidth * 200 / 750 / question.optionsForQuesid.length
        var vertioffset = k * recheight
        var width = option.answers.length / maxnumber * res.windowWidth
        //防止人数为0的时候没有长度显示
        if (width == 0)
          width = 2;

        context.beginPath()
        context.setFillStyle(that.data.color[k % that.data.color.length])
        context.rect(0, vertioffset, width, recheight)
        context.fill()
      }
      wx.drawCanvas({
        canvasId: 'Canvastiaoxing' + parseInt(i + 1),
        actions: context.getActions()
      })

    }
  }
})